package studentManager;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.table.TableModel;

public class Main extends JFrame implements ActionListener {
	TableModel tm;
	JTable jt;
	JScrollPane jsp;
	JPanel jp1, jp2;
	JLabel jl1;
	JButton jb1, jb2, jb3, jb4, jb5, jb6;
	JTextField jtf;
	int rowNum = 1;

	public static void main(String[] args) {
		Main t = new Main();
	}

	public Main() {
		jp1 = new JPanel();
		jtf = new JTextField(10);
		jb1 = new JButton("查询");
		jb1.addActionListener(this);
		jl1 = new JLabel("请输入名字");
		jp1.add(jl1);
		jp1.add(jtf);
		jp1.add(jb1);
		jp2 = new JPanel();
		jb2 = new JButton("添加");
		jb2.addActionListener(this);
		jb3 = new JButton("修改");
		jb3.addActionListener(this);
		jb4 = new JButton("删除");
		jb4.addActionListener(this);
		jb5 = new JButton("上一页");
		jb5.addActionListener(this);
		jb6 = new JButton("下一页");
		jb6.addActionListener(this);
		jp2.add(jb2);
		jp2.add(jb3);
		jp2.add(jb4);
		jp2.add(jb5);
		jp2.add(jb6);
		tm = StuModel.pageStu();
		jt = new JTable(tm);
		jsp = new JScrollPane(jt);
		this.add(jsp);
		this.add(jp1, "North");
		this.add(jp2, "South");
		this.setSize(400, 300);
		this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		this.setVisible(true);
	}

	@Override
	public void actionPerformed(ActionEvent e) {
		if (e.getSource() == jb1) {
			String name = jtf.getText().trim();
			tm = StuModel.pageStu(name, 0, name);
			jt.setModel(tm);
		} else if (e.getSource() == jb2) {
			StuAddDialog sad = new StuAddDialog(this, "添加学生信息", true);
			tm = StuModel.pageStu();
			jt.setModel(tm);
		} else if (e.getSource() == jb3) {
			int rowNum = this.jt.getSelectedRow();
			if (rowNum == -1) {
				JOptionPane.showMessageDialog(this, "请选择一行");
				return;
			}
			StuUpdateDialog sud = new StuUpdateDialog(this, "修改学生信息", true, tm, rowNum);
			tm = StuModel.pageStu();
			jt.setModel(tm);
		} else if (e.getSource() == jb4) {
			int rowNum = this.jt.getSelectedRow();
			if (rowNum == -1) {
				JOptionPane.showMessageDialog(this, "请选择一行");
				return;
			}
			String stuId = (String) tm.getValueAt(rowNum, 0);
			JOptionPane.showMessageDialog(this, StuModel.delStu(stuId) ? "删除成功" : "删除失败");
			tm = StuModel.pageStu();
			jt.setModel(tm);
		} else if (e.getSource() == jb5) {
			tm = StuModel.pageStu("", (--rowNum - 1) * 10, "");
			jt.setModel(tm);
		} else if (e.getSource() == jb6) {
			tm = StuModel.pageStu("", (++rowNum - 1) * 10, "");
			jt.setModel(tm);
		}

	}
}
